package com.test.demo;

import com.test.demo.receive.Receive;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.concurrent.CountDownLatch;

@SpringBootApplication
public class SpringBootRedisMessageApplication {
    private static Logger logger=LoggerFactory.getLogger(SpringBootRedisMessageApplication.class);

    /**
     * 注入消息监听容器
     * @param connectionFactory 连接池
     * @param listenerAdapter 监听适配器
     * @return
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter){
        RedisMessageListenerContainer container=new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //绑定监听者与信道的管理
        container.addMessageListener(listenerAdapter,new PatternTopic("chat"));

        return container;
    }

    /**
     * 指定监听者和监听方法
     * @param receive
     * @return
     */
    @Bean
    MessageListenerAdapter adapter(Receive receive){
        //指定监听者和监听方法
        return new MessageListenerAdapter(receive,"receiveMessage");
    }

    /**
     * 注入消息接受者
     * @param latch
     * @return
     */
    @Bean
    Receive receive(CountDownLatch latch){
        return new Receive(latch);
    }

    @Bean
    CountDownLatch latch(){
        return new  CountDownLatch(1);
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory redisConnectionFactory){
        return new StringRedisTemplate(redisConnectionFactory);
    }

    public static void main(String[] args) throws Exception{
        ApplicationContext ctx= SpringApplication.run(SpringBootRedisMessageApplication.class, args);

        StringRedisTemplate template=ctx.getBean(StringRedisTemplate.class);
        CountDownLatch latch=ctx.getBean(CountDownLatch.class);

        logger.info("send message...");

        template.convertAndSend("chat","Hello from Redis!");

        latch.await();
        System.exit(0);
    }
}
